use std::sync::Arc;

use crate::{services::github_service::GithubService, AppResult, Config};
use actix_web::{http::header, web, HttpResponse};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
struct GithubCallbackQueryParam {
    pub code: String,
}
async fn github_login(
    svr: web::Data<GithubService>,
    cfg: web::Data<Arc<Config>>,
) -> AppResult<HttpResponse> {
    let login_uri = svr.get_login_url(format!("{}/api/v2/github/callback", cfg.app.base_path))?;
    Ok(HttpResponse::Found()
        .insert_header((header::LOCATION, login_uri))
        .finish())
}
async fn github_callback(
    svr: web::Data<GithubService>,
    param: web::Query<GithubCallbackQueryParam>,
) -> AppResult<HttpResponse> {
    let access_token = svr
        .get_access_token_from_code(param.into_inner().code)
        .await?;
    let u = svr.get_user_info_from_access_token(access_token).await?;
    Ok(HttpResponse::Ok().json(u))
}
pub fn configure_github_controller(cfg: &mut web::ServiceConfig) {
    cfg.service(web::resource("/login").route(web::get().to(github_login)))
        .service(web::resource("/callback").route(web::get().to(github_callback)));
}
